package org.znxs.comfriend.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import org.znxs.comfriend.R;
import org.znxs.comfriend.activities.ChatActivity;
import org.znxs.comfriend.adapters.ChatAdapter;
import org.znxs.comfriend.models.User;
import org.znxs.comfriend.utils.AllUserList;
import org.znxs.comfriend.utils.FollowManager;

import java.util.ArrayList;
import java.util.List;

public class MessagesFragment extends Fragment {

    private RecyclerView rvMessages;
    private ChatAdapter adapter;
    private List<User> allUsers; // 存储所有用户数据
    private List<User> followingUsers; // 存储关注中的用户数据

    private FollowManager followManager; // 关注管理器

    private Handler handler; // 定时器使用的 Handler
    private Runnable refreshRunnable; // 定时任务

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_messages, container, false);

        // 初始化消息列表视图
        rvMessages = view.findViewById(R.id.rv_messages);

        // 初始化关注管理器
        followManager = FollowManager.getInstance(requireContext());

        // 设置消息列表
        setupMessageList();

        // 启动定时器
        startRefreshTimer();

        return view;
    }

    private void setupMessageList() {
        rvMessages.setLayoutManager(new LinearLayoutManager(getContext()));

        // 获取所有用户数据
        allUsers = AllUserList.getInstance().getSharedList();

        // 过滤出正在关注的用户
        followingUsers = filterFollowingUsers(allUsers);

        // 设置适配器
        adapter = new ChatAdapter(requireContext(), followingUsers, this::startMessagingActivity);
        rvMessages.setAdapter(adapter);
    }

    /**
     * 过滤出正在关注的用户
     */
    private List<User> filterFollowingUsers(List<User> users) {
        if (users == null || users.isEmpty()) {
            return new ArrayList<>(); // 返回空列表
        }

        List<User> following = new ArrayList<>();
        List<String> followedUserIds = followManager.getList();

        for (User user : users) {
            if (followedUserIds.contains(user.getId())) {
                following.add(user);
            }
        }
        return following;
    }

    /**
     * 启动聊天界面
     */
    private void startMessagingActivity(String userId, String userName, String userAvatarUrl) {
        Intent intent = new Intent(requireContext(), ChatActivity.class); // 修改为 ChatActivity
        intent.putExtra("receiverUserId", userId);
        intent.putExtra("receiverUserName", userName);
        intent.putExtra("receiverUserAvatarUrl", userAvatarUrl);

        startActivity(intent);
    }

    /**
     * 启动定时器，每隔 1 秒刷新一次数据
     */
    private void startRefreshTimer() {
        handler = new Handler();
        refreshRunnable = new Runnable() {
            @Override
            public void run() {
                // 刷新数据
                refreshMessageList();

                // 每隔 1 秒再次执行
                handler.postDelayed(this, 2000);
            }
        };

        // 开始第一次执行
        handler.post(refreshRunnable);
    }

    /**
     * 停止定时器
     */
    private void stopRefreshTimer() {
        if (handler != null && refreshRunnable != null) {
            handler.removeCallbacks(refreshRunnable);
        }
    }

    /**
     * 刷新消息列表
     */
    private void refreshMessageList() {
        // 重新获取关注的用户数据
        followingUsers = filterFollowingUsers(allUsers);

        // 刷新适配器
        adapter.updateData(followingUsers);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        // 停止定时器以避免内存泄漏
        stopRefreshTimer();
    }
}